package com.webflux.demo.controller;

import com.webflux.demo.dao.UserDao;
import com.webflux.demo.modle.User;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @Author RenPu
 * @Date 2023/5/23 10:20
 * @Version 1.0
 * @Description:
 **/

@RestController
@Slf4j
@AllArgsConstructor
public class UserController {


    private final UserDao userDao;


    @RequestMapping("/index")
    public String index(){
        log.info("MVC  ....START...");
        String result = creatStr();
        log.info("MVC  ....END...");
        return result;
    }


    /**
     * 采用的异步方式，通过控制台可以观察出，打印的语句并没有受到线程睡眠时间的影响
     * @return
     */
    @RequestMapping("/index2")
    public Mono<String> index2(){
        log.info("FLUX  ....START...");
        Mono<String> result=Mono.fromSupplier(()->creatStr());
        log.info("FLUX  ....END...");
        return result;

    }



    @RequestMapping(value = "/index3",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> index3(){
        log.info("FLUX  ....START...");
        Flux<String> result=Flux.fromStream(IntStream.range(1,5).mapToObj(i->{
            try {
                TimeUnit.MILLISECONDS.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "flux time"+i;
        }));
        log.info("FLUX  ....END...");
        return result;

    }


    /**
     * webFlux查询数据
     * @return
     */
    @RequestMapping("/findAll")
    public Flux<User> findAll(){
        Flux<User> all = userDao.findAll();
        return all;
    }


    /**
     * webFlux保存数据
     * @return
     */
    @PostMapping("save")
    public Mono<User> save(@RequestBody User user){

        Mono<User> save = userDao.save(user.setAsNew());
        return save;
    }


    /**
     * webFlux根据唯一id值查询对应的数据
     * @return
     */
    @GetMapping("/findById/{id}")
    public Mono<User> findById(@PathVariable Long id){
        Mono<User> save = userDao.findById(id);
        return save;
    }




    /**
     * webFlux根据唯一id值删除对应的数据
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    public Mono deleteById(@PathVariable Long id){
        return userDao.deleteById(id);
    }







    @SneakyThrows
    public String creatStr(){
        TimeUnit.MILLISECONDS.sleep(3000);
        return "hello world";
    }


}
